<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { TableInstanceType } from '@own-basic-component/ui-naive'
import { BaseTableListHelper } from '@own-basic-component/ui-naive'
import projectRequest from '~/api/project'
import type { ProjectVo } from '~/entity/project/project-vo'

const ProjectCard = defineAsyncComponent(() => import('~/components/project/project-card/ProjectCard.vue'))

const baseTableListHelper = ref<TableInstanceType<ProjectVo>>()

const updatePanel = reactive<{
  id?: string
  visible: boolean
  title: string
}>({
  id: '',
  visible: false,
  title: '',
})

const historyPanel = reactive<{
  id: string
  visible: boolean
  title: string
}>({
  id: '',
  visible: false,
  title: '',
})

function handleClickUpdate(id?: string) {
  updatePanel.id = id
  updatePanel.visible = true
  updatePanel.title = id ? '编辑项目' : '添加项目'
}

// 刷新项目列表的事件
function refresh() {
  updatePanel.visible = false
  baseTableListHelper.value!.refresh()
}

// 点击生成历史的事件
function handleClickGenerateHistory(project: ProjectVo) {
  historyPanel.id = project.id
  historyPanel.visible = true
  historyPanel.title = `项目【${project.name}】的生成记录`
}

const router = useRouter()
function go(projectId: string) {
  router.push(`/manage/project/develop/${projectId}`)
}
</script>

<template>
  <BaseTableListHelper
    ref="baseTableListHelper"
    :fetch-method="projectRequest.page"
    :default-rows="10"
    divider-name="项目列表"
  >
    <template #search />
    <template #operation>
      <NButton strong secondary type="primary" @click="handleClickUpdate()">
        <template #icon>
          <span i-carbon-add />
        </template>
        创建工程
      </NButton>
    </template>
    <template #data="{ list }">
      <div flex="~ wrap">
        <ProjectCard
          v-for="item in list as ProjectVo[]"
          :key="item.id"
          :project="item"
          @handle-refresh="refresh"
          @handle-view-history="handleClickGenerateHistory"
          @handle-edit="handleClickUpdate"
          @handle-view="go"
        />
      </div>
    </template>
  </BaseTableListHelper>
  <!--  </div> -->
  <!-- 新增修改页面 -->
  <NDrawer v-model:show="updatePanel.visible" width="40%" placement="right">
    <NDrawerContent v-if="updatePanel.visible" :title="updatePanel.title" closable>
      <UpdateProject :project-id="updatePanel.id" @cancel="updatePanel.visible = false" @refresh="refresh" />
    </NDrawerContent>
  </NDrawer>
  <!-- 生成历史记录 -->
  <NDrawer v-model:show="historyPanel.visible" width="90%" placement="right">
    <GenerateHistoryTable v-if="historyPanel.visible" :project-id="historyPanel.id" :title="historyPanel.title" />
  </NDrawer>
</template>
